package com.shengzai.rdd

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo10ReduceByKey {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("Filter")
    val sc = new SparkContext(conf)
    val stuRDD: RDD[String] = sc.textFile("hadoop_code/src/data/students.txt")
    val mapRDD: RDD[(String, Int)] = stuRDD.map(line => (line.split(",").last, 1))

    val groupByRDD: RDD[(String, Iterable[(String, Int)])] = mapRDD.groupBy(
      _._1
    )
    val groupByRes: RDD[(String, Int)] = groupByRDD.map(
      (tuple2) => {
        (tuple2._1, tuple2._2.size)
      }
    )

    val groupByKeyRDD: RDD[(String, Iterable[Int])] = mapRDD.groupByKey()

    val groupByKeyRes: RDD[(String, Int)] = groupByKeyRDD.map(
      (tuple2) => {
        (tuple2._1, tuple2._2.size)
      }
    )

    val reduceByKeyRes: RDD[(String, Int)] = mapRDD.reduceByKey((x, y) => x + y)
    groupByRes.foreach(println) //shuffle 7.2 KB
    groupByKeyRes.foreach(println)// shuffle 4.1 KB
    reduceByKeyRes.foreach(println) // shuffle 155.0 B

    /**
     * reduceByKey 在Map端会进行预聚合，以减少后续shuffle过程，但是作用范围小。
     * reduceByKey>groupByKey>groupBy
     *
     */

    while (true){

    }

  }

}
